package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.Elevator;
import com.example.entity.ElevatorFaultReason;
import com.example.entity.EmergencyRescue;
import com.example.entity.SpotCheckPlan;
import com.example.entity.authority.PartyUser;
import com.example.entity.authority.SystemUser;
import com.example.ext.entity.ExtElevator;
import com.example.ext.entity.ExtEmergencyRescue;
import com.example.mapp.ElevatorMapp;
import com.example.mapp.EmergencyRescueMapp;
import com.example.mapp.PartyUserMapp;
import com.example.mapp.SysUserMapp;
import com.example.service.EmergencyRescueService;
import com.example.service.MessageNoticeService;
import com.example.util.DateUtils;
import com.example.util.HttpRequestUtils;
import com.example.util.ResultUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Created by youkun on 2017/10/25.
 * 救援表
 */
@Service
public class EmergencyRescueServiceImpl implements EmergencyRescueService {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(EmergencyRescueServiceImpl.class);

    @Autowired
    private EmergencyRescueMapp emergencyRescueMapp;

//	@Autowired
//	private PromotionMapp promotionMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;

    @Autowired
    private SysUserMapp sysUserMapp;

    @Autowired
    private PartyUserMapp partyUserMapp;

    @Autowired
    private MessageNoticeService messageNoticeService;





    /**
     * 查询电梯救援列表
     * @param extEmergencyRescue
     * @return
     */
    @Override
    public Map<String, Object> queryList(ExtEmergencyRescue extEmergencyRescue) {
        List<ExtEmergencyRescue> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtEmergencyRescue> page = PageHelper.startPage(extEmergencyRescue.getCurrentPage(), extEmergencyRescue.getPageSize());
            list = emergencyRescueMapp.findList(extEmergencyRescue);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    /**
     * 查询电梯救援详情
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> queryById(String id) {
        ExtEmergencyRescue emergencyRescue = null;
        try {
            emergencyRescue = emergencyRescueMapp.findById(id);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",emergencyRescue);
    }

    // 与和苏进行数据对接
    @Override
    @Transactional
    public Map<String, Object> add(EmergencyRescue emergencyRescue) {
        try {
            ExtElevator extElevator = elevatorMapp.queryById(emergencyRescue.getElevatorId().toString());
            // 何苏电梯
            if(StringUtils.isNotEmpty(extElevator.getOutElevatorId())){
                // 查询是否有工单
                ExtEmergencyRescue rescue = new ExtEmergencyRescue();
                rescue.setStatus("0");
                rescue.setOutElevatorId(emergencyRescue.getOutElevatorId());
                List<ExtEmergencyRescue> rescueList = emergencyRescueMapp.initWorkOrder(rescue);
                if(rescueList !=null && rescueList.size()>0){
                    // 全部更新
                    for(ExtEmergencyRescue ext:rescueList){
                        emergencyRescue.setStatus("1");
                        emergencyRescue.setId(ext.getId());
                        emergencyRescueMapp.updateRescue(emergencyRescue);
                    }
                    List<String> codeParams = new ArrayList<>();
                    if (StringUtils.isNotEmpty(emergencyRescue.getHumanReasonParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getHumanReasonParam().split(",")));

                    }
                    if (StringUtils.isNotEmpty(emergencyRescue.getOutsideReasonParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getOutsideReasonParam().split(",")));
                    }

                    if (StringUtils.isNotEmpty(emergencyRescue.getDoorSystemParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getDoorSystemParam().split(",")));
                    }

                    if (StringUtils.isNotEmpty(emergencyRescue.getTractionSystemParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getTractionSystemParam().split(",")));
                    }

                    if (StringUtils.isNotEmpty(emergencyRescue.getGuideSystemParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getGuideSystemParam().split(",")));
                    }

                    if (StringUtils.isNotEmpty(emergencyRescue.getBridgeCabinParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getBridgeCabinParam().split(",")));
                    }

                    if (StringUtils.isNotEmpty(emergencyRescue.getControlSystemParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getControlSystemParam().split(",")));
                    }
                    if (StringUtils.isNotEmpty(emergencyRescue.getElectricSystemParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getElectricSystemParam().split(",")));
                    }
                    if (StringUtils.isNotEmpty(emergencyRescue.getSafeRefinementParam())) {
                        codeParams.addAll(Arrays.asList(emergencyRescue.getSafeRefinementParam().split(",")));
                    }

                    String httpUrl = "http://dev.hesutech.com:81/bpalercxdi/lms/lms_restrain_info";
                    Map<String, Object> map = new HashMap<>();
                    List<Map<String, Object>> list = new ArrayList<>();
                    Elevator elevator = elevatorMapp.elevatorByOutId(emergencyRescue);
                    // 获取电梯96333编码
                    String tag_96333 = "";
                    String accepter = "";
                    String accepter_phone = "";
                    if (elevator != null) {
                        if (StringUtils.isNotEmpty(elevator.getOutsideNum())) {
                            tag_96333 = elevator.getOutsideNum();
                        }
                        if (StringUtils.isNotEmpty(elevator.getSafeUserId().toString())) {
                            SystemUser systemUser = sysUserMapp.queryById(elevator.getSafeUserId().toString());
                            if (systemUser != null) {
                                accepter = systemUser.getUserName();
                                accepter_phone = systemUser.getPhone();
                            }
                        }
                    }
                    if (codeParams != null && codeParams.size() > 0) {
                        for (String code : codeParams) {
                            Map<String, Object> param = new HashMap<>();
                            param.put("lift_sys_id", emergencyRescue.getOutElevatorId());
                            param.put("tag_96333", tag_96333);
                            param.put("alarm_man", emergencyRescue.getAlarmBy());
                            param.put("alarm_phone", emergencyRescue.getAlarmByPhone1());
                            param.put("barrier_type", emergencyRescue.getAlarmType());
                            param.put("barrier_date", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            param.put("barrier_content", emergencyRescue.getAlarmContent());
                            param.put("send_time", emergencyRescue.getCreateDate());
                            param.put("arrival_time", emergencyRescue.getArrivedTime());
                            param.put("completion_time", emergencyRescue.getReceivedTime());
                            // 接单人就是电梯的安全管理员
                            param.put("accepter", accepter);
                            param.put("accepter_phone", accepter_phone);
                            param.put("data_time", emergencyRescue.getCreateDate());
                            param.put("fault_sys_id", emergencyRescue.getId().toString());
                            param.put("fault_code", code);
                            list.add(param);
                        }
                    }
                    map.put("lms_restrain_info", list);
                    JSONObject jsonObject = new JSONObject(map);
                    String sendPost = HttpRequestUtils.sendPost(httpUrl, jsonObject, null);
                    System.out.println(sendPost);
                }else{
                    emergencyRescueMapp.add(emergencyRescue);
                }
            }else{
                // 华阳电梯
                emergencyRescueMapp.add(emergencyRescue);
            }
        } catch (Exception e) {
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("新增失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("新增成功",null);
    }

    /**
     * 初始化电梯故障原因
     */
    @Override
    public Map<String, Object> initFaultList() {
        Map<String, List<ElevatorFaultReason>> param = new HashMap<>();
        try {
            List<ElevatorFaultReason> list = emergencyRescueMapp.initFaultList();
            if (list != null && list.size() > 0) {
                for (ElevatorFaultReason faultReason : list) {
                    if (param.containsKey(faultReason.getTypeEn())) {
                        param.get(faultReason.getTypeEn()).add(faultReason);
                    } else {
                        List<ElevatorFaultReason> reasons = new ArrayList<>();
                        reasons.add(faultReason);
                        param.put(faultReason.getTypeEn(), reasons);
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败" + e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("查询成功", param);
    }

    @Override
    @Transactional
    public Map<String, Object> addWorkOrder(EmergencyRescue emergencyRescue) {
        Map<String, Object> resultMap = new HashMap<>();
        String message = "新增成功";
        try {
            if(StringUtils.isNotEmpty(emergencyRescue.getOutElevatorId())){
                emergencyRescue.setStatus("0");
                emergencyRescueMapp.add(emergencyRescue);
                // 根据外部关联码查询电梯信息
                Elevator elevator  = elevatorMapp.elevatorByOutId(emergencyRescue);
                // 获取电梯安全管理员
                String userIds = elevator.getSafeUserId().toString();
                List<String> userIdList = Arrays.asList(userIds.split(","));
                // 获取单位Id
                PartyUser partyUser = partyUserMapp.findById(userIds);

                // 封装数据
                Map parm = new HashMap();
                parm.put("id", partyUser.getPartyId());
                parm.put("userIdList", userIdList);
                parm.put("sendUserId", userIds);
                parm.put("content", "您收到了应急救援通知，电梯编号：" + elevator.getElevatorNum() + "\n 电梯地址：" + emergencyRescue.getAlarmAddress() + "\n 请尽快前去救援，完成任务工单！");
                parm.put("title", "应急救援通知");
                messageNoticeService.batchMsg(parm);
            }else{
                return ResultUtil.returnError("新增失败：故障电梯为空",resultMap);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("新增失败"+e.getMessage(),resultMap);
        }
        return ResultUtil.returnSuccess(message,resultMap);
    }

    /**
     * 初始化数据
     * @param extEmergencyRescue
     * @return
     */
    @Override
    public Map<String, Object> initWorkOrder(ExtEmergencyRescue extEmergencyRescue) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Page<EmergencyRescue> page = PageHelper.startPage(extEmergencyRescue.getCurrentPage(), extEmergencyRescue.getPageSize());
            List<ExtEmergencyRescue> list =  emergencyRescueMapp.initWorkOrder(extEmergencyRescue);
            map.put("list", list);
            map.put("total", page.getTotal());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }


}
